package service

import (
	"blog-server/global"
	"blog-server/models"
	"blog-server/models/views"
	"blog-server/utils/codes"
	"blog-server/utils/exception"
	utils "blog-server/utils/file"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

type FileService struct{}

func NewFileService() *FileService {
	return &FileService{}
}

// Upload 文件上传处理
func (file *FileService) Upload(params views.FileUploadVo) (*models.FileSync, error) {
	var fileModel *models.FileSync
	if params.IsDir {
		count, _ := global.Engine.Where("can_view = ?", true).Where("file_or_dir = 1").Count(&models.FileSync{})
		if params.FileName == "" {
			if count <= 0 {
				params.FileName = "新建文件夹"
			} else {
				params.FileName = "新建文件夹" + strconv.Itoa(int(count))
			}
		}
		fileModel = models.NewDirFileSync(params.FileName, params.ParentId, params.Brief)
	} else {
		fileInfo := params.File
		split := strings.Split(fileInfo.Filename, ".")
		split[0] = codes.MD5(split[0])
		newPath := filepath.Join(global.Config.FileConfig.BasePath, time.Now().Format("2006-01-02"))
		timeStr := time.Now().Format("2006-01-02")
		fileModel = models.NewFileSync(
			fileInfo.Filename,
			filepath.Join(timeStr, strings.Join(split, ".")),
			split[1],
			fileInfo.Size,
			params.ParentId,
			params.Brief,
		)
		if err := utils.WriterFile(params.File, newPath, strings.Join(split, ".")); err != nil {
			return nil, err
		}
	}
	_, err := global.Engine.InsertOne(&fileModel)
	if err != nil {
		return nil, err
	}
	return fileModel, nil
}

// FileInfo 文件详情
// param value 文件记录ID
func (file *FileService) FileInfo(value string) (string, []byte, error) {
	var fileModel models.FileSync
	err := global.Engine.Where("id = ?", value).Find(&FileService{})
	if err != nil {
		return "", nil, err
	}
	readFile, err := utils.ReadFile(global.Config.FileConfig.BasePath, fileModel.FilePath)
	if err != nil {
		return "", nil, err
	}
	return fileModel.FileName, readFile, nil
}

// FileList 文件列表
func (file *FileService) FileList(params views.FileListVo) ([]models.FileSync, error) {
	var dataList []models.FileSync
	err := global.Engine.Where("can_view = true and parent_id = ?", params.ParentId).Desc("file_or_dir").Asc("update_time").Find(&dataList)
	if err != nil {
		return nil, exception.NewSysError(err.Error())
	}
	return dataList, nil
}
